/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution{
public:
  ListNode *removeElements(ListNode *head, int val){

    ListNode *dummyHead = new ListNode(-1, head);
    ListNode *pre = dummyHead;
    ListNode *p = head;

    while(p != nullptr){
      if(p->val == val){
        pre->next = p->next;
        delete p;
        p = pre->next;
      }else{
        p = p->next;
        pre = pre->next;
      }
    }

    // 此处要返回dummyHead->next，因为有可能已经把head所在的元素给delete掉了
    return dummyHead->next;

  }
};